const { createApp, ref, computed, onMounted, watch, h } = Vue;

// 修改会话模块
const sessionManager = {
    setup() {
        const selectedKey = ref('');
        const editorMode = ref('text');
        const textValue = ref('');
        const message = ref({ text: '', type: '' });
        const sortedKeys = ref([]);
        const jsonEditor = ref(null);

        // 获取当前标签页的sessionStorage数据
        async function getCurrentTabSessionStorage() {
            try {
                const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
                
                // 检查特殊URL，包括chrome://, edge://, about:等
                if (tab.url.startsWith('chrome://') || 
                    tab.url.startsWith('edge://') || 
                    tab.url.startsWith('about:') ||
                    tab.url.startsWith('chrome-extension://')) {
                    return {};
                }

                const result = await chrome.scripting.executeScript({
                    target: { tabId: tab.id },
                    func: () => {
                        const items = {};
                        for (let i = 0; i < sessionStorage.length; i++) {
                            const key = sessionStorage.key(i);
                            items[key] = sessionStorage.getItem(key);
                        }
                        return items;
                    }
                });
                return result[0].result;
            } catch (error) {
                console.error('Error getting sessionStorage:', error);
                showMessage('无法访问此页面的会话存储', 'error');
                return {};
            }
        }

        // 更新选择框中的keys
        async function updateKeyList() {
            const storage = await getCurrentTabSessionStorage();
            sortedKeys.value = Object.keys(storage).sort();
            
            // 如果存在mainMsg，则自动选中它，否则选中第一个
            const mainMsgIndex = sortedKeys.value.findIndex(key => key === 'mainMsg');
            if (mainMsgIndex !== -1) {
                selectedKey.value = 'mainMsg';
                loadValue('mainMsg');
            } else if (sortedKeys.value.length > 0) {
                selectedKey.value = sortedKeys.value[0];
                loadValue(sortedKeys.value[0]);
            }
        }

        // 加载选中key的值
        async function loadValue(key) {
            const storage = await getCurrentTabSessionStorage();
            const value = storage[key];
            
            if (isJSON(value)) {
                editorMode.value = 'json';
                textValue.value = formatJSON(value);
                if (jsonEditor.value) {
                    jsonEditor.value.set(JSON.parse(value));
                }
            } else {
                editorMode.value = 'text';
                textValue.value = value;
            }
        }

        // 检查字符串是否为JSON格式
        function isJSON(str) {
            try {
                JSON.parse(str);
                return true;
            } catch (e) {
                return false;
            }
        }

        // 格式化JSON
        function formatJSON(jsonString) {
            try {
                const obj = JSON.parse(jsonString);
                return JSON.stringify(obj, null, 2);
            } catch (e) {
                showMessage('Invalid JSON format', 'error');
                return jsonString;
            }
        }

        // 显示消息
        function showMessage(text, type) {
            message.value = { text, type };
            setTimeout(() => {
                message.value = { text: '', type: '' };
            }, 3000);
        }

        // 保存值
        async function saveValue() {
            if (!selectedKey.value) return;

            let value;
            if (editorMode.value === 'json') {
                try {
                    if (!jsonEditor.value) {
                        throw new Error('JSON editor not initialized');
                    }
                    value = JSON.stringify(jsonEditor.value.get());
                } catch (e) {
                    showMessage('Invalid JSON format', 'error');
                    return;
                }
            } else {
                value = textValue.value;
                if (editorMode.value === 'json') {
                    try {
                        JSON.parse(value);
                    } catch (e) {
                        showMessage('Invalid JSON format', 'error');
                        return;
                    }
                }
            }

            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
            await chrome.scripting.executeScript({
                target: { tabId: tab.id },
                args: [selectedKey.value, value],
                func: (key, value) => {
                    sessionStorage.setItem(key, value);
                }
            });

            showMessage('保存成功', 'success');
        }

        // 在新标签页中打开
        async function openInNewTab() {
            if (!selectedKey.value) return;

            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
            const storage = await getCurrentTabSessionStorage();
            const value = storage[selectedKey.value];

            const editorUrl = chrome.runtime.getURL('editor.html') + 
                `?tabId=${tab.id}&key=${encodeURIComponent(selectedKey.value)}&value=${encodeURIComponent(value)}`;

            chrome.tabs.create({ url: editorUrl });
            window.close();
        }

        return {
            selectedKey,
            editorMode,
            textValue,
            message,
            jsonEditor,
            sortedKeys,
            updateKeyList,
            loadValue,
            saveValue,
            openInNewTab,
            showMessage,
            isEditorVisible: computed(() => !!selectedKey.value)
        };
    }
};

// 拦截响应模块
const ajaxMonitor = {
    setup() {
        const requests = ref([]);
        const searchText = ref('');
        const selectedTab = ref(null);
        const selectedDomain = ref(null);

        // 计算属性
        const requestCount = computed(() => requests.value.length);
        const filteredRequests = computed(() => {
            let filtered = requests.value;
            
            // 按标签页筛选
            if (selectedTab.value) {
                filtered = filtered.filter(req => req.tabId === selectedTab.value);
            }
            
            // 按域名筛选
            if (selectedDomain.value) {
                filtered = filtered.filter(req => req.domain === selectedDomain.value);
            }
            
            // 按搜索文本筛选
            const text = searchText.value.toLowerCase();
            if (text) {
                filtered = filtered.filter(req => 
                    (req.txcode || '').toLowerCase().includes(text) ||
                    (req.url || '').toLowerCase().includes(text)
                );
            }
            
            return filtered;
        });

        // 计算属性：按标签页和域名组织的请求
        const groupedRequests = computed(() => {
            const groups = {};
            requests.value.forEach(req => {
                const tabId = req.tabId || 'unknown';
                const domain = req.domain || 'unknown';
                
                if (!groups[tabId]) {
                    groups[tabId] = {
                        id: tabId,
                        title: req.tabTitle || 'Unknown Tab',
                        url: req.tabUrl || '',
                        domains: {}
                    };
                }
                
                if (!groups[tabId].domains[domain]) {
                    groups[tabId].domains[domain] = {
                        name: domain,
                        requests: []
                    };
                }
                
                groups[tabId].domains[domain].requests.push(req);
            });
            return groups;
        });

        // 计算属性：标签页列表
        const tabList = computed(() => {
            return Object.values(groupedRequests.value).map(tab => ({
                id: tab.id,
                title: tab.title,
                url: tab.url,
                count: Object.values(tab.domains).reduce((sum, domain) => 
                    sum + domain.requests.length, 0
                )
            }));
        });

        // 计算属性：当前标签页的域名列表
        const domainList = computed(() => {
            if (!selectedTab.value || !groupedRequests.value[selectedTab.value]) {
                return [];
            }
            
            return Object.values(groupedRequests.value[selectedTab.value].domains)
                .map(domain => ({
                    name: domain.name,
                    count: domain.requests.length
                }));
        });

        function downloadResponse(request) {
            const blob = new Blob([JSON.stringify(request.responseData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${request.txcode || 'response'}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function exportAllData() {
            const data = {
                requests: requests.value,
                groupedRequests: groupedRequests.value,
                selectedTab: selectedTab.value,
                selectedDomain: selectedDomain.value,
                timestamp: new Date().toISOString()
            };
            
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `ajax-monitor-data-${new Date().toISOString()}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        function toggleExpand(request) {
            request.isExpanded = !request.isExpanded;
        }

        async function clearRequests() {
            if (selectedTab.value || selectedDomain.value) {
                // 清除特定标签页或域名的请求
                const newRequests = requests.value.filter(req => {
                    if (selectedTab.value && req.tabId !== selectedTab.value) return true;
                    if (selectedDomain.value && req.domain !== selectedDomain.value) return true;
                    return false;
                });
                requests.value = newRequests;
                await chrome.storage.local.set({ ajaxRequests: newRequests });
            } else {
                // 清除所有请求
                requests.value = [];
                await chrome.storage.local.set({ ajaxRequests: [] });
            }
        }

        // 获取当前标签页ID
        async function getCurrentTabId() {
            try {
                const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
                return tab?.id;
            } catch (error) {
                console.error('Error getting current tab:', error);
                return null;
            }
        }

        async function loadRequests() {
            const { ajaxRequests = [] } = await chrome.storage.local.get(['ajaxRequests']);
            requests.value = ajaxRequests.map(req => ({
                ...req,
                isExpanded: false
            }));

            // 自动选择当前标签页
            const currentTabId = await getCurrentTabId();
            if (currentTabId) {
                console.log('Auto selecting current tab:', currentTabId);
                selectedTab.value = currentTabId;
            }
        }

        return {
            requests,
            searchText,
            selectedTab,
            selectedDomain,
            requestCount,
            filteredRequests,
            groupedRequests,
            tabList,
            domainList,
            downloadResponse,
            exportAllData,
            toggleExpand,
            clearRequests,
            loadRequests
        };
    }
};

// 二维码生成模块
const qrcodeGenerator = {
    setup() {
        const qrcodeText = ref('');
        const errorMessage = ref('');
        let qrcode = null;

        // 处理粘贴事件
        function handlePaste(e) {
            const items = e.clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    e.preventDefault();
                    const blob = items[i].getAsFile();
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        const img = new Image();
                        img.onload = function() {
                            // 创建canvas来处理图片
                            const canvas = document.createElement('canvas');
                            canvas.width = img.width;
                            canvas.height = img.height;
                            const ctx = canvas.getContext('2d');
                            ctx.drawImage(img, 0, 0);
                            
                            // 获取图片数据
                            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                            
                            // 使用jsQR解析二维码
                            const code = jsQR(imageData.data, imageData.width, imageData.height);
                            
                            if (code) {
                                qrcodeText.value = code.data;
                                errorMessage.value = '成功从图片中解析二维码';
                                setTimeout(() => {
                                    errorMessage.value = '';
                                }, 2000);
                            } else {
                                errorMessage.value = '未能从图片中识别出二维码';
                                setTimeout(() => {
                                    errorMessage.value = '';
                                }, 2000);
                            }
                        };
                        img.src = event.target.result;
                    };
                    reader.readAsDataURL(blob);
                    return;
                }
            }
        }

        // 获取合适的QR码配置
        function getQRConfig(text) {
            const byteLength = encodeURIComponent(text).replace(/%[0-9A-F]{2}/g, '_').length;
            
            // 使用更保守的配置
            if (byteLength <= 100) {
                return {
                    correctLevel: QRCode.CorrectLevel.H  // 30% 纠错
                };
            } else if (byteLength <= 250) {
                return {
                    correctLevel: QRCode.CorrectLevel.Q  // 25% 纠错
                };
            } else {
                return {
                    correctLevel: QRCode.CorrectLevel.L  // 7% 纠错
                };
            }
        }

        // 检查文本长度并返回合适的QR码版本和建议
        function checkTextLength(text) {
            if (!text || text.trim() === '') {
                return {
                    valid: false,
                    message: '请输入要生成二维码的文本'
                };
            }

            // 使用 encodeURIComponent 来准确计算 UTF-8 字节长度
            const byteLength = encodeURIComponent(text).replace(/%[0-9A-F]{2}/g, '_').length;

            // 使用更保守的长度限制
            const MAX_LENGTH = 300;

            if (byteLength <= MAX_LENGTH) {
                return {
                    valid: true,
                    message: byteLength > 250 ? '注意：文本较长，已降低纠错级别以确保生成成功' : ''
                };
            } else {
                return {
                    valid: false,
                    message: `文本太长（${byteLength} 字节，建议单个二维码不超过 ${MAX_LENGTH} 字节）。已自动分段处理。`
                };
            }
        }

        // 生成二维码
        function generateQRCode(text) {
            if (!text || text.trim() === '') {
                errorMessage.value = '请输入要生成二维码的文本';
                return;
            }

            const lengthCheck = checkTextLength(text);
            if (!lengthCheck.valid) {
                errorMessage.value = lengthCheck.message;
                return;
            }

            errorMessage.value = lengthCheck.message;  // 显示警告信息（如果有）
            
            try {
                const qrcodeContainer = document.getElementById('qrcode');
                if (!qrcodeContainer) {
                    console.error('QR code container not found');
                    return;
                }

                // 清除之前的内容
                qrcodeContainer.innerHTML = '';
                
                // 获取合适的配置
                const config = getQRConfig(text.trim());
                
                // 重新创建二维码实例
                qrcode = new QRCode(qrcodeContainer, {
                    text: text.trim(),
                    width: 256,
                    height: 256,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: config.correctLevel
                });
            } catch (error) {
                console.error('QR Code generation error:', error);
                errorMessage.value = '生成二维码时出错：' + error.message;
            }
        }

        // 分段生成多个二维码
        function generateMultipleQRCodes(text) {
            if (!text || text.trim() === '') {
                errorMessage.value = '请输入要生成二维码的文本';
                return;
            }

            // 使用更保守的分段长度
            const MAX_LENGTH = 250;  // 使用更保守的长度，确保生成成功
            const chunks = [];
            const trimmedText = text.trim();
            
            // 分段
            for (let i = 0; i < trimmedText.length; i += MAX_LENGTH) {
                chunks.push(trimmedText.slice(i, i + MAX_LENGTH));
            }

            try {
                // 清除现有内容
                const container = document.getElementById('qrcode');
                if (!container) {
                    console.error('QR code container not found');
                    return;
                }

                container.innerHTML = '';

                // 为每个分段创建二维码
                chunks.forEach((chunk, index) => {
                    const wrapper = document.createElement('div');
                    wrapper.className = 'qrcode-wrapper';
                    
                    const label = document.createElement('div');
                    label.className = 'qrcode-label';
                    label.textContent = `第 ${index + 1}/${chunks.length} 部分`;
                    
                    const qrcodeDiv = document.createElement('div');
                    wrapper.appendChild(label);
                    wrapper.appendChild(qrcodeDiv);
                    container.appendChild(wrapper);

                    // 获取合适的配置
                    const config = getQRConfig(chunk);

                    new QRCode(qrcodeDiv, {
                        text: chunk,
                        width: 256,
                        height: 256,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: config.correctLevel
                    });
                });

                errorMessage.value = chunks.length > 1 
                    ? `文本已被分成 ${chunks.length} 个二维码` 
                    : '';

            } catch (error) {
                console.error('QR Code generation error:', error);
                errorMessage.value = '生成二维码时出错：' + error.message;
            }
        }

        // 下载二维码
        function downloadQRCode() {
            const canvas = document.querySelectorAll('#qrcode canvas');
            if (!canvas || canvas.length === 0) {
                errorMessage.value = '没有可下载的二维码';
                return;
            }

            try {
                if (canvas.length === 1) {
                    // 单个二维码下载
                    const url = canvas[0].toDataURL('image/png');
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'qrcode.png';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                } else {
                    // 多个二维码打包下载
                    canvas.forEach((c, index) => {
                        const url = c.toDataURL('image/png');
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `qrcode-part${index + 1}.png`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    });
                }
            } catch (error) {
                console.error('QR Code download error:', error);
                errorMessage.value = '下载二维码时出错：' + error.message;
            }
        }

        // 在新标签页中打开
        function openInNewTab() {
            const editorUrl = chrome.runtime.getURL('qrcode.html');
            chrome.tabs.create({ url: editorUrl });
            window.close();
        }

        watch(qrcodeText, (newText) => {
            if (!newText || newText.trim() === '') {
                const container = document.getElementById('qrcode');
                if (container) {
                    container.innerHTML = '';
                }
                errorMessage.value = '';
                return;
            }

            const lengthCheck = checkTextLength(newText);
            if (lengthCheck.valid) {
                generateQRCode(newText);
            } else {
                generateMultipleQRCodes(newText);
            }
        });

        // 在 onMounted 中添加粘贴事件监听
        onMounted(() => {
            const textarea = document.querySelector('.qrcode-input');
            if (textarea) {
                textarea.addEventListener('paste', handlePaste);
            }
        });

        return {
            qrcodeText,
            errorMessage,
            downloadQRCode,
            openInNewTab
        };
    }
};

// 测试环境模块
const testEnvironment = {
    setup() {
        const link = ref('');
        const linkParams = ref({});
        const ifLock = ref(false);
        const allBookmark = ref([]);
        let SCHOOLID = '';
        let APPID = '';
        let selectDate = null;

        // 从localStorage获取书签
        function getBookMarks() {
            let obj = localStorage.getItem("LL");
            if (obj) {
                try {
                    obj = JSON.parse(obj);
                } catch (error) {
                    obj = {};
                }
            } else {
                obj = {};
            }
            return obj;
        }

        // 查询书签
        function queryBM4Local(val) {
            const obj = getBookMarks();
            return obj[val];
        }

        // 删除书签
        function deleteBookmark(val) {
            const obj = getBookMarks();
            delete obj[val];
            localStorage.setItem("LL", JSON.stringify(obj));
            updateBookmark();
            return true;
        }

        // 添加书签
        function addBM2Local(name, href) {
            const obj = getBookMarks();
            localStorage.setItem("LL", JSON.stringify({ ...obj, [name]: href }));
        }

        // 解析URL参数
        function parseSearch(str) {
            return str.split("&").reduce((obj, current) => {
                const arr = current.split("=");
                arr[0] = arr[0].replace(/^\?/, '');
                obj[arr[0]] = arr[1];
                return obj;
            }, {});
        }

        // 更新书签列表
        function updateBookmark() {
            allBookmark.value = [];
            const bmks = getBookMarks();
            for (const key in bmks) {
                if (Object.hasOwnProperty.call(bmks, key)) {
                    const element = bmks[key];
                    try {
                        const schoolIdMatch = element.match(/SCHOOLID=([^&]*)/);
                        const studentIdMatch = element.match(/STUDENTID=([^&]*)/);
                        allBookmark.value.push({
                            value: element,
                            name: key,
                            SCHOOLID: schoolIdMatch ? schoolIdMatch[1] : '',
                            STUDENTID: studentIdMatch ? studentIdMatch[1] : ''
                        });
                    } catch (error) {
                        console.error('Error parsing bookmark:', error);
                    }
                }
            }
        }

        // 切换书签
        function switchTo(e) {
            link.value = e.target.value;
            syncUrl();
        }

        // 同步URL参数
        function syncUrl() {
            const a = document.createElement('a');
            a.href = link.value;
            linkParams.value = { 
                path: a.protocol + "//" + a.host + a.pathname, 
                ...parseSearch(a.search) 
            };
            
            if (ifLock.value && APPID && SCHOOLID) {
                linkParams.value = { ...linkParams.value, APPID, SCHOOLID };
            }
            
            APPID = linkParams.value.APPID;
            SCHOOLID = linkParams.value.SCHOOLID;
        }

        // 添加新书签
        function addBookmark() {
            const name = prompt("书签名称");
            if (typeof name === "string") {
                const bookmarkName = name || 'default';
                const value = queryBM4Local(bookmarkName);
                let finalName = bookmarkName;
                
                if (value) {
                    const shouldOverwrite = confirm(`书签【${bookmarkName}】已经存在，是否覆盖？`);
                    if (!shouldOverwrite) {
                        finalName = bookmarkName + "_" + Date.now();
                    }
                }
                
                addBM2Local(finalName, targetUrl.value);
                updateBookmark();
            }
        }

        // 日期变更处理
        function dateChange(e) {
            selectDate = e.target.value.replace(/[^\d]/g, '');
        }

        // 右键菜单处理
        function onContextMenu(name) {
            if (confirm(`是否删除书签：${name}?`)) {
                deleteBookmark(name);
            }
        }

        // 计算目标URL
        const targetUrl = computed(() => {
            const params = Object.keys(linkParams.value).reduce((previousValue, currentValue) => {
                if (currentValue === "path") { return previousValue; }
                return previousValue + (previousValue ? "&" : "") + currentValue + "=" + linkParams.value[currentValue];
            }, "");
            return linkParams.value.path ? (linkParams.value.path + "?" + params) : '';
        });

        // 自动更新时间戳
        function startTimer() {
            setInterval(() => {
                if (!linkParams.value.TM) return;
                
                const date = new Date(Date.now() + 8 * 3600000);
                linkParams.value.TM = date.toJSON().replace(/[^\d]/g, '').substr(0, 14);
                if (selectDate) {
                    linkParams.value.TM = linkParams.value.TM.replace(/\d{8}/, selectDate);
                }
            }, 1000);
        }

        // 初始化
        onMounted(() => {
            link.value = queryBM4Local('textarea') || '';
            if (link.value) {
                syncUrl();
            }
            updateBookmark();
            startTimer();

            // 添加示例书签
            addBM2Local("示例云桌面", "http://128.196.189.100:8101/LHECISM/B2CMainPlat_00?TXCODE=YXDL02&BRANCHID=555000000&SERVLET_NAME=B2CMainPlat_00&CCB_IBSVersion=V6&PT_STYLE=10&APPID=102004&APPNAME=testapp&OPENID=&SCHOOLID=10486&STUDENTID=2021092410011&PHONENUM=&NAME=&IDTYPE=&IDNO=&USERID=&TM=20211104083633");
            addBM2Local("示例119", "http://128.192.182.208/LHECISM/B2CMainPlat_00?TXCODE=YXDL02&BRANCHID=555000000&SERVLET_NAME=B2CMainPlat_00&CCB_IBSVersion=V6&PT_STYLE=10&APPID=102004&APPNAME=testapp&OPENID=&SCHOOLID=10486&STUDENTID=2021092410011&PHONENUM=&NAME=&IDTYPE=&IDNO=&USERID=&TM=20211104083633");
        });

        // 监听link变化
        watch(link, (val) => {
            addBM2Local('textarea', val);
        });

        return {
            link,
            linkParams,
            ifLock,
            allBookmark,
            targetUrl,
            switchTo,
            syncUrl,
            addBookmark,
            dateChange,
            onContextMenu
        };
    }
};

// 登录E码通模块
const loginEMT = {
    setup() {
        const schoolId = ref('10001');
        const openid = ref('oZThW450OemWKwffrIEbn3Y44usY');
        const generatedUrl = ref('');
        const copyStatus = ref('');  // 添加复制状态提示
        const schoolOptions = [
            { id: '35040002', name: '默认学校' },
            { id: '37150003', name: '聊城二中' },
            { id: '14407', name: '广舞' },
            { id: '13390', name: '枣庄科技职业学院' },
            { id: '37020005', name: '青岛理工' },
            { id: '10316', name: '中国药科' },
            { id: '13667', name: '广州商' },
            { id: 'temp6982091', name: '南方学院番禺' },
            { id: '10001', name: '学校10001' }
        ];
        
        const openidOptions = [
            { id: 'oZThW45LMTJGKOwFshP5vJH4RW3g', name: '肖琳' },
            { id: 'oZThW450OemWKwffrIEbn3Y44usY', name: '我' },
            { id: 'oZThW42wLlcxSLyRvRhatDQdc9vc', name: '小明' },
            { id: 'oZThW46-S6cSp7527zt1kJFeSBkQ', name: '小金' },
            { id: 'oZThW44m3CWe9W-u2cjJatev6Q0c', name: '王磊' },
            { id: 'oZThW4wEu0b6HIyAYBUAk8mGWHso', name: '永远' }
        ];

        async function generateUrl() {
            try {
                const response = await fetch("https://app.xiaoyuan.ccb.com/LHECISM/B2CMainPlat_00", {
                    "headers": {
                        "accept": "*/*",
                        "content-type": "application/x-www-form-urlencoded",
                        "sec-fetch-dest": "empty",
                        "sec-fetch-mode": "cors",
                        "sec-fetch-site": "cross-site"
                    },
                    "referrer": "https://servicewechat.com/wx796af3381abe60e0/devtools/page-frame.html",
                    "referrerPolicy": "strict-origin-when-cross-origin",
                    "body": `openid=${openid.value}&schoolId=${schoolId.value}&encryptedData=encryptedData&iv=iv&resCode=resCode&USERID=&SKEY=&BRANCHID=555000000&SERVLET_NAME=B2CMainPlat_00&CCB_IBSVersion=V6&PT_STYLE=10&TXCODE=DZ0095&TOPAGE=2`,
                    "method": "POST",
                    "mode": "cors",
                    "credentials": "include"
                });

                const data = await response.json();
                console.log(data);
                
                if (data.data && data.data.ccbParam) {
                    generatedUrl.value = `https://app.xiaoyuan.ccb.com/LHECISM/CCBYXxcxLgServiceReqServlet?ccbParam=${data.data.ccbParam}`;
                    console.log('Generated URL:', generatedUrl.value);
                } else {
                    alert('生成链接失败：' + (data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('生成链接失败:', error);
                alert('生成链接失败：' + error.message);
            }
        }

        function openUrl() {
            if (generatedUrl.value) {
                window.open(generatedUrl.value);
            }
        }

        function copyUrl() {
            if (generatedUrl.value) {
                navigator.clipboard.writeText(generatedUrl.value).then(() => {
                    copyStatus.value = '已复制';
                    setTimeout(() => {
                        copyStatus.value = '';
                    }, 2000);
                }).catch(err => {
                    console.error('复制失败:', err);
                    copyStatus.value = '复制失败';
                    setTimeout(() => {
                        copyStatus.value = '';
                    }, 2000);
                });
            }
        }

        return {
            schoolId,
            openid,
            generatedUrl,
            copyStatus,
            schoolOptions,
            openidOptions,
            generateUrl,
            openUrl,
            copyUrl
        };
    }
};

// 登录E码通UI组件
const LoginEMTTab = {
    props: ['active', 'login'],
    setup(props) {
        if (!props.login) {
            console.error('Login props is required for LoginEMTTab');
            return () => h('div', 'Error: Login data not provided');
        }

        return () => h('div', {
            id: 'login-tab',
            class: ['tab-content', { active: props.active }]
        }, [
            h('div', { class: 'login-container' }, [
                // SchoolId 输入框和自动完成
                h('div', { class: 'input-group' }, [
                    h('label', 'School ID'),
                    h('input', {
                        type: 'text',
                        value: props.login.schoolId.value,
                        onInput: (e) => props.login.schoolId.value = e.target.value,
                        placeholder: '请输入或选择学校ID',
                        list: 'schoolList'
                    }),
                    h('datalist', { id: 'schoolList' }, 
                        props.login.schoolOptions.map(school => 
                            h('option', { value: school.id }, `${school.name} (${school.id})`)
                        )
                    )
                ]),

                // OpenID 输入框和自动完成
                h('div', { class: 'input-group' }, [
                    h('label', 'Open ID'),
                    h('input', {
                        type: 'text',
                        value: props.login.openid.value,
                        onInput: (e) => props.login.openid.value = e.target.value,
                        placeholder: '请输入或选择OpenID',
                        list: 'openidList'
                    }),
                    h('datalist', { id: 'openidList' }, 
                        props.login.openidOptions.map(user => 
                            h('option', { value: user.id }, `${user.name} (${user.id})`)
                        )
                    )
                ]),

                // 生成链接按钮
                h('button', {
                    class: 'login-button',
                    onClick: props.login.generateUrl
                }, '生成链接'),

                // 显示生成的链接
                props.login.generatedUrl.value && h('div', { class: 'generated-url' }, [
                    h('div', { class: 'url-text' }, props.login.generatedUrl.value),
                    h('div', { class: 'button-group' }, [
                        h('button', {
                            class: 'copy-url-button',
                            onClick: props.login.copyUrl
                        }, props.login.copyStatus.value || '复制链接'),
                        h('button', {
                            class: 'open-url-button',
                            onClick: props.login.openUrl
                        }, '打开链接')
                    ])
                ])
            ])
        ]);
    }
};

// 测试环境UI组件
const TestTab = {
    props: ['active', 'test'],
    setup(props) {
        if (!props.test) {
            console.error('Test props is required for TestTab');
            return () => h('div', 'Error: Test data not provided');
        }

        return () => h('div', {
            id: 'test-tab',
            class: ['tab-content', { active: props.active }]
        }, [
            h('div', { class: 'test-container' }, [
                // 文本输入区域
                h('textarea', {
                    value: props.test.link.value,
                    onInput: (e) => props.test.link.value = e.target.value,
                    cols: 100,
                    rows: 10
                }),
                
                // 解析按钮
                h('button', {
                    onClick: props.test.syncUrl
                }, 'parse'),

                // 书签选择器
                h('select', {
                    onChange: props.test.switchTo
                }, props.test.allBookmark.value.map(item => 
                    h('option', {
                        value: item.value,
                        key: item.name
                    }, item.name)
                )),

                // 锁定学校渠道选项
                h('div', { class: 'checkbox-container' }, [
                    h('input', {
                        type: 'checkbox',
                        id: 'lockshl',
                        checked: props.test.ifLock.value,
                        onInput: (e) => props.test.ifLock.value = e.checked
                    }),
                    h('label', { for: 'lockshl' }, '锁定学校渠道')
                ]),

                // 参数编辑区域
                Object.keys(props.test.linkParams.value).map(key => 
                    h('div', { class: 'param-item' }, [
                        h('span', { class: 'label' }, key),
                        key === 'TM' 
                            ? h('input', {
                                type: 'date',
                                onChange: props.test.dateChange
                            })
                            : h('input', {
                                type: 'text',
                                value: props.test.linkParams.value[key],
                                onInput: (e) => props.test.linkParams.value[key] = e.target.value
                            })
                    ])
                ),

                // 目标URL显示
                h('div', { class: 'target-url' }, [
                    h('a', {
                        href: props.test.targetUrl.value,
                        target: '_blank'
                    }, props.test.targetUrl.value)
                ]),

                // 添加书签按钮
                h('div', { 
                    class: 'add-bookmark',
                    onClick: props.test.addBookmark
                }, '存'),

                // 书签列表
                h('div', { class: 'bookmark-list' }, 
                    props.test.allBookmark.value.map(item => 
                        h('div', { class: 'bookmark-item' }, [
                            h('span', {
                                class: 'bookmark-name',
                                onClick: () => {
                                    props.test.link.value = item.value;
                                    props.test.syncUrl();
                                },
                                onContextmenu: (e) => {
                                    e.preventDefault();
                                    props.test.onContextMenu(item.name);
                                }
                            }, item.name),
                            h('span', { class: 'bookmark-value' }, ': ' + item.value)
                        ])
                    )
                )
            ])
        ]);
    }
};

// 修改会话UI组件
const SessionTab = {
    props: ['active', 'session'],  // 声明组件的props
    setup(props) {
        if (!props.session) {
            console.error('Session props is required for SessionTab');
            return () => h('div', 'Error: Session data not provided');
        }

        return () => h('div', {
            id: 'session-tab',
            class: ['tab-content', { active: props.active }]
        }, [
            h('div', { class: 'container' }, [
                // 左侧列表
                h('div', { class: 'storage-list' }, [
                    h('select', {
                        size: 5,
                        value: props.session.selectedKey.value,
                        onInput: (e) => props.session.selectedKey.value = e.target.value
                    }, props.session.sortedKeys.value.map(key => 
                        h('option', { value: key }, key)
                    ))
                ]),

                // 右侧编辑器
                h('div', { 
                    class: ['editor-container', { active: props.session.isEditorVisible.value }] 
                }, [
                    h('div', { class: 'editor-header' }, [
                        h('div', { class: 'value-type' }, [
                            h('label', [
                                h('input', {
                                    type: 'radio',
                                    checked: props.session.editorMode.value === 'text',
                                    onChange: () => props.session.editorMode.value = 'text'
                                }),
                                ' Text'
                            ]),
                            h('label', [
                                h('input', {
                                    type: 'radio',
                                    checked: props.session.editorMode.value === 'json',
                                    onChange: () => props.session.editorMode.value = 'json'
                                }),
                                ' JSON'
                            ])
                        ]),
                        h('button', {
                            class: 'icon-button',
                            title: 'Open in New Tab',
                            onClick: props.session.openInNewTab
                        }, [
                            h('svg', {
                                viewBox: '0 0 24 24',
                                width: 16,
                                height: 16
                            }, [
                                h('path', {
                                    fill: 'currentColor',
                                    d: 'M19 19H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'
                                })
                            ])
                        ])
                    ]),
                    h('div', { 
                        class: ['json-editor', { active: props.session.editorMode.value === 'json' }] 
                    }),
                    h('textarea', {
                        id: 'valueEditor',
                        class: { active: props.session.editorMode.value === 'text' },
                        value: props.session.textValue.value,
                        onInput: (e) => props.session.textValue.value = e.target.value
                    }),
                    h('div', { class: 'button-container' }, [
                        props.session.editorMode.value === 'text' && h('button', {
                            onClick: () => props.session.formatJSON(props.session.textValue.value)
                        }, 'Format JSON'),
                        h('button', {
                            onClick: props.session.saveValue
                        }, 'Save')
                    ].filter(Boolean)),
                    props.session.message.value.text && h('div', {
                        class: ['message', props.session.message.value.type]
                    }, props.session.message.value.text)
                ])
            ])
        ]);
    }
};

// 拦截响应UI组件
const AjaxTab = {
    props: ['active', 'ajax'],  // 声明组件的props
    setup(props) {
        if (!props.ajax) {
            console.error('Ajax props is required for AjaxTab');
            return () => h('div', 'Error: Ajax data not provided');
        }

        return () => h('div', {
            id: 'ajax-tab',
            class: ['tab-content', { active: props.active }]
        }, [
            h('div', { id: 'ajax-container' }, [
                // 过滤器区域
                h('div', { class: 'ajax-header' }, [
                    h('div', { class: 'ajax-controls' }, [
                        h('button', {
                            class: 'clear-button',
                            onClick: props.ajax.clearRequests
                        }, props.ajax.selectedTab.value || props.ajax.selectedDomain.value ? 'Clear Selected' : 'Clear All'),
                        props.ajax.selectedTab.value && h('button', {
                            class: 'secondary',
                            onClick: () => {
                                props.ajax.selectedTab.value = null;
                                props.ajax.selectedDomain.value = null;
                            }
                        }, 'Show All'),
                        h('button', {
                            class: 'export-button',
                            onClick: props.ajax.exportAllData
                        }, 'Export Data')
                    ]),
                    h('div', { class: 'ajax-filter' }, [
                        h('input', {
                            type: 'text',
                            placeholder: 'Search TXCODE or URL...',
                            value: props.ajax.searchText.value,
                            onInput: (e) => props.ajax.searchText.value = e.target.value
                        })
                    ])
                ]),

                // 标签页列表
                h('div', { class: 'tab-list' }, 
                    props.ajax.tabList.value.map(tab => 
                        h('div', {
                            class: ['tab-item', { active: props.ajax.selectedTab.value === tab.id }],
                            onClick: () => {
                                props.ajax.selectedTab.value = props.ajax.selectedTab.value === tab.id ? null : tab.id;
                                props.ajax.selectedDomain.value = null;
                            }
                        }, [
                            h('div', { class: 'tab-info' }, [
                                h('div', { class: 'tab-title' }, tab.title),
                                h('div', { class: 'tab-url' }, tab.url)
                            ]),
                            h('span', { class: 'request-count' }, tab.count)
                        ])
                    )
                ),

                // 域名列表
                props.ajax.selectedTab.value && h('div', { class: 'domain-list' },
                    props.ajax.domainList.value.map(domain =>
                        h('div', {
                            class: ['domain-item', { active: props.ajax.selectedDomain.value === domain.name }],
                            onClick: () => {
                                props.ajax.selectedDomain.value = props.ajax.selectedDomain.value === domain.name ? null : domain.name;
                            }
                        }, [
                            h('span', { class: 'domain-name' }, domain.name),
                            h('span', { class: 'request-count' }, domain.count)
                        ])
                    )
                ),

                // 请求列表
                h('div', { class: 'request-list' }, 
                    props.ajax.filteredRequests.value.map(request => 
                        h('div', { class: 'request-item' }, [
                            h('div', {
                                class: 'request-header',
                                onClick: () => props.ajax.toggleExpand(request)
                            }, [
                                h('div', { class: 'request-info' }, [
                                    h('span', { class: 'request-txcode' }, request.txcode || 'Unknown'),
                                    h('span', { class: 'request-domain' }, request.domain),
                                    h('span', { class: 'request-time' }, request.time)
                                ]),
                                h('div', { class: 'request-actions' }, [
                                    h('button', {
                                        class: 'download-button',
                                        onClick: (e) => {
                                            e.stopPropagation();
                                            props.ajax.downloadResponse(request);
                                        }
                                    }, '下载')
                                ])
                            ]),
                            h('div', {
                                class: ['request-body', { expanded: request.isExpanded }]
                            }, [
                                h('div', { class: 'request-section' }, [
                                    h('h4', '请求体'),
                                    h('pre', JSON.stringify(request.requestBody || {}, null, 2))
                                ]),
                                h('div', { class: 'request-section' }, [
                                    h('h4', '响应体'),
                                    h('pre', JSON.stringify(request.responseData || {}, null, 2))
                                ])
                            ])
                        ])
                    )
                )
            ])
        ]);
    }
};

// 二维码UI组件
const QRCodeTab = {
    props: ['active', 'qrcode'],
    setup(props) {
        if (!props.qrcode) {
            console.error('QRCode props is required for QRCodeTab');
            return () => h('div', 'Error: QRCode data not provided');
        }

        return () => h('div', {
            id: 'qrcode-tab',
            class: ['tab-content', { active: props.active }]
        }, [
            h('div', { class: 'qrcode-container' }, [
                h('div', { class: 'input-container' }, [
                    h('div', { class: 'input-header' }, [
                        h('button', {
                            class: 'icon-button',
                            title: 'Open in New Tab',
                            onClick: props.qrcode.openInNewTab
                        }, [
                            h('svg', {
                                viewBox: '0 0 24 24',
                                width: 16,
                                height: 16
                            }, [
                                h('path', {
                                    fill: 'currentColor',
                                    d: 'M19 19H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'
                                })
                            ])
                        ])
                    ]),
                    h('textarea', {
                        class: 'qrcode-input',
                        placeholder: '请输入要生成二维码的文本',
                        value: props.qrcode.qrcodeText.value,
                        onInput: (e) => props.qrcode.qrcodeText.value = e.target.value
                    }),
                    props.qrcode.errorMessage.value && h('div', { 
                        class: 'error-message' 
                    }, props.qrcode.errorMessage.value)
                ]),
                h('div', { id: 'qrcode', class: 'qrcode-display' }),
                h('div', { class: 'qrcode-actions' }, [
                    h('button', {
                        class: 'download-button',
                        onClick: props.qrcode.downloadQRCode
                    }, '下载二维码')
                ])
            ])
        ]);
    }
};

// 截图控制模块
const screenshotControl = {
    setup() {
        const enabled = ref(true);
        const message = ref('');
        const messageType = ref('');  // 'success' 或 'error'
        const urlInput = ref('');     // 新增：URL输入
        const nameInput = ref('');    // 新增：名称输入
        const savedUrls = ref([]);    // 新增：保存的URL列表

        // 初始化时获取存储的状态
        onMounted(async () => {
            const result = await chrome.storage.local.get(['screenshotEnabled', 'savedUrls']);
            enabled.value = result.screenshotEnabled !== false;
            savedUrls.value = result.savedUrls || [];
        });

        // 监听状态变化
        watch(enabled, (newValue) => {
            chrome.storage.local.set({ screenshotEnabled: newValue });
        });

        // 显示消息
        function showMessage(text, type = 'success') {
            message.value = text;
            messageType.value = type;
            setTimeout(() => {
                message.value = '';
                messageType.value = '';
            }, 3000);
        }

        // 立即截图
        async function takeScreenshotNow() {
            try {
                const response = await chrome.runtime.sendMessage({ type: 'TAKE_SCREENSHOT_NOW' });
                if (response.success) {
                    showMessage('截图成功', 'success');
                } else {
                    showMessage(response.error || '截图失败', 'error');
                }
            } catch (error) {
                showMessage(error.message || '截图失败', 'error');
            }
        }

        // 验证URL或锚点格式
        function isValidUrlOrAnchor(str) {
            // 如果是以#开头的锚点
            if (str.startsWith('#')) {
                return true;
            }

            // 否则验证是否为有效URL
            try {
                new URL(str);
                return true;
            } catch (e) {
                return false;
            }
        }

        // 新增：保存URL
        async function saveUrl() {
            if (!urlInput.value || !nameInput.value) {
                showMessage('请输入URL和名称', 'error');
                return;
            }

            // 验证URL或锚点格式
            if (!isValidUrlOrAnchor(urlInput.value)) {
                showMessage('请输入有效的URL或锚点', 'error');
                return;
            }

            const newUrl = {
                url: urlInput.value,
                name: nameInput.value
            };

            const updatedUrls = [...savedUrls.value, newUrl];
            await chrome.storage.local.set({ savedUrls: updatedUrls });
            savedUrls.value = updatedUrls;

            // 清空输入
            urlInput.value = '';
            nameInput.value = '';
            showMessage('保存成功', 'success');
        }

        // 新增：删除URL
        async function deleteUrl(index) {
            const updatedUrls = savedUrls.value.filter((_, i) => i !== index);
            await chrome.storage.local.set({ savedUrls: updatedUrls });
            savedUrls.value = updatedUrls;
            showMessage('删除成功', 'success');
        }

        // 新增：跳转到URL
        async function navigateToUrl(url) {
            try {
                const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
                
                // 如果是锚点
                if (url.startsWith('#')) {
                    // 获取当前页面的URL
                    const currentUrl = tab.url;
                    
                    // 如果当前URL已经包含#，则替换它
                    const baseUrl = currentUrl.split('#')[0];
                    const newUrl = baseUrl + url.replace(/#/g, "#/");
                    
                    // 先更新URL
                    await chrome.tabs.update(tab.id, { url: newUrl });
                     
                } else {
                    // 否则跳转到新URL
                    await chrome.tabs.update(tab.id, { url });
                }
                window.close(); // 关闭弹窗
            } catch (error) {
                showMessage('跳转失败: ' + error.message, 'error');
            }
        }

        return {
            enabled,
            message,
            messageType,
            urlInput,
            nameInput,
            savedUrls,
            takeScreenshotNow,
            saveUrl,
            deleteUrl,
            navigateToUrl
        };
    }
};

// 截图控制UI组件
const ScreenshotControlTab = {
    props: ['active', 'screenshot'],
    setup(props) {
        if (!props.screenshot) {
            console.error('Screenshot control props is required');
            return () => h('div', 'Error: Screenshot control data not provided');
        }

        return () => h('div', {
            class: ['screenshot-control', { active: props.active }]
        }, [
            h('div', { class: 'control-container' }, [
                // 自动截图开关
                h('div', { class: 'switch-group' }, [
                    h('label', { class: 'switch' }, [
                        h('input', {
                            type: 'checkbox',
                            checked: props.screenshot.enabled.value,
                            onChange: (e) => props.screenshot.enabled.value = e.target.checked
                        }),
                        h('span', { class: 'slider' })
                    ]),
                    h('span', { class: 'control-label' }, 
                        props.screenshot.enabled.value ? '自动截图已开启' : '自动截图已关闭'
                    )
                ]),
                
                // 立即截图按钮
                h('button', {
                    class: 'screenshot-now-button',
                    onClick: props.screenshot.takeScreenshotNow
                }, '立即截图'),

                // URL管理区域
                h('div', { class: 'url-manager' }, [
                    // URL输入区域
                    h('div', { class: 'url-input-group' }, [
                        h('input', {
                            type: 'text',
                            placeholder: '输入URL',
                            value: props.screenshot.urlInput.value,
                            onInput: (e) => props.screenshot.urlInput.value = e.target.value
                        }),
                        h('input', {
                            type: 'text',
                            placeholder: '输入名称',
                            value: props.screenshot.nameInput.value,
                            onInput: (e) => props.screenshot.nameInput.value = e.target.value
                        }),
                        h('button', {
                            onClick: props.screenshot.saveUrl,
                            class: 'save-url-button'
                        }, '保存')
                    ]),

                    // URL按钮列表
                    h('div', { class: 'url-button-list' }, 
                        props.screenshot.savedUrls.value.map((item, index) => 
                            h('div', { class: 'url-button-wrapper' }, [
                                h('button', {
                                    class: 'url-button',
                                    onClick: () => props.screenshot.navigateToUrl(item.url)
                                }, item.name),
                                h('button', {
                                    class: 'delete-url-button',
                                    onClick: () => props.screenshot.deleteUrl(index)
                                }, '×')
                            ])
                        )
                    )
                ])
            ]),
            
            // 消息提示
            props.screenshot.message.value && h('div', {
                class: ['screenshot-message', props.screenshot.messageType.value]
            }, props.screenshot.message.value)
        ]);
    }
};

// 主应用
const app = createApp({
    setup() {
        // 状态
        const currentTab = ref('session');

        // 初始化各个模块
        const session = sessionManager.setup();
        const ajax = ajaxMonitor.setup();
        const qrcode = qrcodeGenerator.setup();
        const test = testEnvironment.setup();
        const login = loginEMT.setup();
        const screenshot = screenshotControl.setup();

        // 标签页配置
        const tabs = [
            { id: 'session', name: '修改会话' },
            { id: 'ajax', name: '拦截响应' },
            { id: 'qrcode', name: '二维码生成' },
            { id: 'test', name: '测试环境' },
            { id: 'login', name: '登录E码通' },
            { id: 'screenshot', name: '截图控制' }
        ];

        // 监听器
        watch(session.selectedKey, (newKey) => {
            if (newKey) {
                session.loadValue(newKey);
            }
        });

        watch(session.editorMode, (mode) => {
            if (mode === 'json' && session.textValue.value) {
                try {
                    const jsonValue = JSON.parse(session.textValue.value);
                    if (session.jsonEditor.value) {
                        session.jsonEditor.value.set(jsonValue);
                    }
                } catch (e) {
                    session.showMessage('Current value is not valid JSON', 'error');
                    session.editorMode.value = 'text';
                }
            }
        });

        // 初始化
        onMounted(() => {
            // 初始化 JSON 编辑器
            const container = document.querySelector('.json-editor');
            console.log(container,'===========');
            
            if (container) {
                session.jsonEditor.value = new JSONEditor(container, {
                    mode: 'tree',
                    modes: ['tree', 'code'],
                    sortObjectKeys: true,
                    onChangeText: (jsonString) => {
                        session.textValue.value = jsonString;
                    },
                    onError: (err) => {
                        console.error('JSONEditor error:', err);
                    },
                    onModeChange: (newMode, oldMode) => {
                        console.log('Mode changed from', oldMode, 'to', newMode);
                    }
                });
            }

            // 加载数据
            session.updateKeyList();
            ajax.loadRequests();

            // 监听存储变化
            chrome.storage.onChanged.addListener((changes) => {
                if (changes.ajaxRequests) {
                    ajax.loadRequests();
                }
            });
        });

        // 渲染函数
        function render() {
            return h('div', [
                // 标签页按钮
                h('div', { class: 'tab-container' }, 
                    tabs.map(tab => h('button', {
                        class: ['tab-button', { active: currentTab.value === tab.id }],
                        onClick: () => currentTab.value = tab.id
                    }, [
                        h('span', tab.name),
                        tab.id === 'ajax' && h('span', { class: 'request-count' }, ajax.requestCount.value)
                    ].filter(Boolean)))
                ),

                // 各个标签页内容
                h(SessionTab, { 
                    active: currentTab.value === 'session', 
                    session: session 
                }),
                h(AjaxTab, { 
                    active: currentTab.value === 'ajax', 
                    ajax: ajax 
                }),
                h(QRCodeTab, { 
                    active: currentTab.value === 'qrcode', 
                    qrcode: qrcode 
                }),
                h(TestTab, {
                    active: currentTab.value === 'test',
                    test: test
                }),
                h(LoginEMTTab, {
                    active: currentTab.value === 'login',
                    login: login
                }),
                h(ScreenshotControlTab, {
                    active: currentTab.value === 'screenshot',
                    screenshot: screenshot
                })
            ]);
        }

        return {
            render
        };
    },

    render() {
        return this.render();
    }
});

app.mount('#app');

document.addEventListener('DOMContentLoaded', function() {
    console.log('Popup DOMContentLoaded');
    
    // 恢复上次打开的标签页
    chrome.storage.local.get(['lastActiveTab'], function(result) {
        console.log('Retrieved lastActiveTab:', result.lastActiveTab);
        if (result.lastActiveTab) {
            const tabButton = document.querySelector(`.tab-button:nth-child(${
                {'session': 1, 'ajax': 2, 'qrcode': 3, 'test': 4, 'login': 5, 'screenshot': 6}[result.lastActiveTab] || 1
            })`);
            console.log('Found tab button:', tabButton);
            if (tabButton) {
                tabButton.click();
            }
        }
    });

    // 监听标签页切换
    const tabButtons = document.querySelectorAll('.tab-button');
    console.log('Found tab buttons:', tabButtons.length);
    
    tabButtons.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除数字和特殊字符，只保留中文名称
            const tabName = this.textContent.trim().replace(/[0-9]+$/, '').trim();
            console.log('Processing tab text:', this.textContent, '-> cleaned:', tabName);
            
            const tabMapping = {
                '修改会话': 'session',
                '拦截响应': 'ajax',
                '二维码生成': 'qrcode',
                '测试环境': 'test',
                '登录E码通': 'login',
                '截图控制': 'screenshot'
            };
            const mappedTab = tabMapping[tabName];
            console.log('Tab clicked:', tabName, '-> mapped to:', mappedTab);
            
            chrome.storage.local.set({
                lastActiveTab: mappedTab
            }, () => {
                console.log('Saved lastActiveTab:', mappedTab);
            });
        });
    });
});